<?php

namespace app\common\logic;
use addons\adszone\library\Adszone;
use app\admin\controller\Zlog;
use app\common\model\chat\ChatUser;
use app\common\model\course\Chapter;
use app\common\model\course\Course;
use app\common\model\course\Order;
use Monolog\Handler\IFTTTHandler;
use think\Db;
use think\Exception;
use think\exception\ValidateException;


/**
 * 统计热门课程
 */
class CourseLogic
{
    protected $model;
    protected $org_cate_id = ORG_CATE_ID;
    protected $field = ['id', 'name','introduce', 'origin_price', 'price', 'visitor_origin_price', 'visitor_price', 'buy_numbers', 'image', 'thumbs','is_system','org_cate_id','is_chat'];
    public function __construct()
    {
//        $where['org_cate_id'] = $this->org_cate_id;
        $where['status'] = 0;
//        $where['org_cate_id'] = ['neq', 0];
        $this->model = (new Course())->where($where);
    }

    public function getSeries($series_id)
    {
        $pic = new Adszone();
        $images = $pic->getAdsByMark('chat_series',ORG_CATE_ID);
        $info = Db::name('series')->where('id', $series_id)->find();
        if($info){
            $info['is_system'] = 2;
            $info['chapters'] = Db::name('learn_course')->where(['series_id'=>$info['id']])->count();
            if(empty($info['image'])){
                $info['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
            }
        }
        return $info;
    }

    /*
     * 获取课程信息
     * $user 用户
     * $course_id 课程id
     * 处理访客课程价格
     * */
    public function getCourse($course_id, $field = null) {
        $search = $this->field;
        if ($field !== null) {
            $search = $field;
        }
        $info = $this->model->where('id', $course_id)->field($search)->find();
        if(empty($info)){
            return array();
        }
        //判断课程是否被购买
        $order = Order::get(['user_id'=> UID, 'learn_course_id'=> $course_id, 'type'=> 1]);

        if($info['is_system'] == 1){
            $info['chapters'] = 1;
        }else{
            $info['chapters'] = Db::name('learn_course_system')->where(['sys_id'=> $course_id])->count();
        }
        if ($order || $info['price'] == 0) {
            $info['is_buy'] = 1; //1为已经购买
        } else {
            $info['is_buy'] = 0;  //0为未购买
        }
        //判断课程是否被点赞
        $thumbs = Db::name('learn_course_thumbs')->where(['user_id'=> UID, 'learn_course_id'=> $course_id])->count();

        if ($thumbs > 0) {
            $info['is_thumbs'] = 1; //1为已经点赞
        } else {
            $info['is_thumbs'] = 0;  //0为未点赞
        }

        if (VISITOR == 2) {
            $info['price'] = $info['visitor_price'];
            $info['origin_price'] = $info['visitor_origin_price'];
        }
        if(ORG_TYPE  == 2 && $info['org_cate_id'] == 0 && VISITOR != 2){
            $info['price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $course_id,'org_cate_id'=>ORG_CATE_ID])->value('price');
            $info['origin_price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $course_id,'org_cate_id'=>ORG_CATE_ID])->value('origin_price');
        }
        $pic = new Adszone();
        $images = $pic->getAdsByMark('course_img',ORG_CATE_ID);
        if (empty($info['image'])) {
            $info['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
        }
        if($info['is_chat'] == 1){
            $room_info = Db::name('chat_room')->where('edu_learn_course_id', $course_id)->field('talk_id,start_time,end_time,room_id')->find();
            $info['room_id'] = isset($room_info['room_id'])?$room_info['room_id']:'';
            $chat_info = Db::name('chat_info')->where('edu_learn_course_id', $course_id)->field('*')->select();
            if($chat_info){
                foreach($chat_info as &$val){
                    $val['text'] = unserialize($val['text']);
                    $val['text'] = json_encode($val['text']);
                }
                $info['chat_info'] = $chat_info;
            }
            $info['chat_info_video'] = isset($chat_info['video'])?$chat_info['video']:'';
            $info['chat_info_text'] = isset($chat_info['text'])?$chat_info['text']:'';

        }else{
            $info['chat_info_video'] = '';
            $info['chat_info_text'] = '';
        }
        unset($info['visitor_price']);
        unset($info['visitor_origin_price']);
        return $info->append(['images_arr'])->toArray();
    }

    /**
     * 点赞操作
     * @param $course_id
     * @param $type 1点赞 2取消
     */
    public function doThumbs($course_id, $type)
    {
        try {
            if($type == 1){
                $this->model->where(['id'=> $course_id])->setInc('thumbs', 1);
                Db::name('learn_course_thumbs')->insert(['user_id'=> UID, 'learn_course_id'=> $course_id]);
            }else{
                $this->model->where(['id'=> $course_id])->setDec('thumbs', 1);
                Db::name('learn_course_thumbs')->where(['user_id'=> UID, 'learn_course_id'=> $course_id])->delete();
            }
            return true;
        } catch (Exception $e) {
            echo $e->getMessage();
            return false;
        }
    }
    /**
     * 往期直播
     */
    public function getHistory($series_id) {
        $where['is_chat'] = 1;
        $where['is_single'] = 1;
        $res = Db::name('learn_course')->alias('c')
            ->join('edu_chat_room r', 'c.id = r.edu_learn_course_id', 'left')
            ->where('c.series_id', $series_id)
            ->where('c.is_system', 1)
            ->where('c.is_chat', 1)
            ->where('r.type = 3 or r.type is null')
            ->column('c.id');
        if(!empty($res)){
            $where['id'] = ['in', $res];
        }else{
            $where['id'] = ['<', 0];
        }
        $search = $this->field;
        $list = $this->model
            ->where($where)
            ->field($search)
            ->order('org_cate_id', 'asc')
            ->order('is_hot', 'desc')
            ->order('createtime desc')
            ->paginate(100)->each(function($item, $key){
                $pic = new Adszone();
                $images = $pic->getAdsByMark('course_img',ORG_CATE_ID);
                if (VISITOR == 2) {
                    $item['price'] = $item['visitor_price'];
                    $item['origin_price'] = $item['visitor_origin_price'];
                }
                if(ORG_TYPE  == 2 && $item['org_cate_id'] == 0 && VISITOR != 2){
                    $item['price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $item['id'],'org_cate_id'=>ORG_CATE_ID])->value('price');
                    $item['origin_price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $item['id'],'org_cate_id'=>ORG_CATE_ID])->value('origin_price');
                }
                if (empty($item['image'])) {
                    $item['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
                }
                if($item['is_system'] == 1){
                    $item['chapters'] = 1;
                }else{
                    $item['chapters'] = Db::name('learn_course_system')->where(['sys_id'=> $item['id']])->count();
                }
                if($item['is_chat'] == 1){//直播课程
                    $chat_info = Db::name('chat_room')->where('edu_learn_course_id', $item['id'])->field('talk_id,start_time,end_time,room_id')->find();
                    $item['talk_info'] = ChatUser::get($chat_info['talk_id']);
                    $item['start_time'] = $chat_info['start_time'];
                    $item['end_time'] = $chat_info['end_time'];
                    $item['room_id'] = $chat_info['room_id'];
                }
                unset($item['visitor_price']);
                unset($item['visitor_origin_price']);
            });
        $list = $list->toArray();
        return $list;
    }

    /*获取课程列表*/
    public function getList($where = [], $limit = 15 ,$order = 'createtime desc',$field = null) {
        $search = $this->field;
        if ($field !== null) {
            $search = $field;
        }
        $list = $this->model
            ->where($where)
            ->where('is_single', 1)
            ->field($search)
            ->order('org_cate_id', 'asc')
            ->order('is_hot', 'desc')
            ->order($order)
            ->paginate($limit)->each(function($item, $key){
                $pic = new Adszone();
                $images = $pic->getAdsByMark('course_img',ORG_CATE_ID);
                if (VISITOR == 2) {
                    $item['price'] = $item['visitor_price'];
                    $item['origin_price'] = $item['visitor_origin_price'];
                }
                if(ORG_TYPE  == 2 && $item['org_cate_id'] == 0 && VISITOR != 2){
                    $item['price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $item['id'],'org_cate_id'=>ORG_CATE_ID])->value('price');
                    $item['origin_price'] = Db::name('learn_course_orgpay')->where(['course_id'=> $item['id'],'org_cate_id'=>ORG_CATE_ID])->value('origin_price');
                }
                if (empty($item['image'])) {
                    $item['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
                }
                if($item['is_system'] == 1){
                    $item['chapters'] = 1;
                }else{
                    $item['chapters'] = Db::name('learn_course_system')->where(['sys_id'=> $item['id']])->count();
                }
                if($item['is_chat'] == 1){//直播课程
                    $chat_info = Db::name('chat_room')->where('edu_learn_course_id', $item['id'])->field('talk_id,start_time,end_time,room_id')->find();
                    $item['talk_info'] = ChatUser::get($chat_info['talk_id']);
                    $item['start_time'] = $chat_info['start_time'];
                    $item['end_time'] = $chat_info['end_time'];
                    $item['room_id'] = $chat_info['room_id'];
                }
                unset($item['visitor_price']);
                unset($item['visitor_origin_price']);
            });
        $list = $list->toArray();
        if(isset($where['is_chat']) && $where['is_chat'] == 1){
            $pic = new Adszone();
            $images = $pic->getAdsByMark('chat_series',ORG_CATE_ID);
            $arr = Db::name('series')->where('org_cate_id', ORG_CATE_ID)->select();
            if($arr){
                foreach($arr as &$val){
                    $val['is_system'] = 2;
                    $val['chapters'] = Db::name('learn_course')->where(['series_id'=>$val['id'],'status'=>0])->count();
                    $val['courses'] = Db::name('learn_course')->alias('c')
                        ->join('edu_chat_room r', 'c.id = r.edu_learn_course_id', 'left')
                        ->where('c.series_id', $val['id'])
                        ->where('c.status', 0)
                        ->where('r.type = 3 or r.type is null')->count();
                    if(empty($val['image'])){
                        $val['image'] = isset($images['data'][0]['imageurl'])?$images['data'][0]['imageurl']:'';
                    }
                }
            }
            $list = array_merge($list['data'], $arr);
        }
        return $list;
    }

    /*获取课程章节列表*/
    public function getChapters($course_id) {
        $where['sys_id'] = $course_id;
        $ids = Db::name('learn_course_system')->where('sys_id', $course_id)->column('course_id');
        $list = array();
        if($ids){
            $list = Db::name('learn_course')->where('id','in', $ids)->field('*')->select();
            if($list){
                foreach ($list as &$val){
                    if(stripos( $val['file'],'.mp3') === false){
                        $val['is_movie'] = 1;
                    }else{
                        $val['is_movie'] = 2;
                    }
                }
            }
        }

//        $where['org_cate_id'] = $this->org_cate_id;
//        $chapter = new Chapter();
//        $list = $chapter->where($where)->field(true)->order('sort asc')->select();
        return $list;
    }

}
